package com.mofeng.myshop.interceptor;

import com.beust.jcommander.IVariableArity;
import com.mofeng.myshop.domain.vo.user.UserVo;
import com.mofeng.myshop.service.user.UserUtilsService;
import com.mofeng.myshop.until.LoginUserThreadLocalUtil;
import com.mofeng.myshop.until.TimeOutUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDate;
import java.util.Date;

@Order(Ordered.HIGHEST_PRECEDENCE)//优先级最高
@Component
@RequiredArgsConstructor
public class ThreadLocalInterceptor implements HandlerInterceptor {

    private final UserUtilsService userUtilsService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 存储登录用户
        UserVo userVo = userUtilsService.parseToken();
        LoginUserThreadLocalUtil.set(userVo);

        TimeOutUtil.isTimeOut();
        return true; // 返回 true 表示继续执行后续的拦截器和处理器
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理之后但是在视图被渲染之前调用，可以对 ModelAndView 进行修改
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后调用，无论请求处理成功还是失败都会调用
        LoginUserThreadLocalUtil.remove();
    }
}
